const { Sequelize } = require('sequelize');
require('dotenv').config();

// 从环境变量获取数据库配置
const dbConfig = {
  database: process.env.DB_NAME,
  username: process.env.DB_USER,
  password: process.env.DB_PASS,
  host: process.env.DB_HOST,
  port: process.env.DB_PORT || 3306,
  dialect: process.env.DB_DIALECT || 'mysql',
  storage: process.env.DB_STORAGE
};

let sequelize;

if (process.env.DB_DIALECT === 'sqlite') {
  // 使用SQLite
  sequelize = new Sequelize({
    dialect: 'sqlite',
    storage: dbConfig.storage || './database.sqlite',
    logging: process.env.NODE_ENV === 'development' ? console.log : false
  });
} else {
  // 使用MySQL
  sequelize = new Sequelize(
    dbConfig.database,
    dbConfig.username,
    dbConfig.password,
    {
      host: dbConfig.host,
      port: dbConfig.port,
      dialect: dbConfig.dialect,
      logging: process.env.NODE_ENV === 'development' ? console.log : false,
      pool: {
        max: 5,
        min: 0,
        acquire: 60000,
        idle: 10000
      },
      dialectOptions: {
        connectTimeout: 60000
      }
    }
  );
}

// 数据库连接函数，优化错误提示
const connectDB = async () => {
  try {
    // 先尝试连接数据库
    await sequelize.authenticate();
    
    if (process.env.DB_DIALECT === 'sqlite') {
      console.log('✅ SQLite 数据库连接成功');
    } else {
      console.log('✅ MySQL 数据库服务器连接成功');
      
      // 检查MySQL数据库是否存在，如果不存在则创建
      const queryInterface = sequelize.getQueryInterface();
      const databases = await queryInterface.sequelize.query(
        `SHOW DATABASES LIKE '${dbConfig.database}';`,
        { type: queryInterface.sequelize.QueryTypes.SHOW_DATABASES }
      );

      if (databases[0].length === 0) {
        console.log(`🗄️  数据库 ${dbConfig.database} 不存在，正在创建...`);
        await queryInterface.sequelize.query(
          `CREATE DATABASE ${dbConfig.database} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`
        );
        console.log(`✅ 数据库 ${dbConfig.database} 创建成功`);
        
        // 重新连接到新创建的数据库
        await sequelize.close();
        await sequelize.authenticate();
      }
    }

    // 种子脚本需要强制同步表结构
    if (process.env.NODE_ENV === 'development' || process.argv.includes('seed')) {
      console.log('🔄 正在同步数据库表结构...');
      // 种子模式下使用force确保表结构正确
      const syncOptions = process.argv.includes('seed') ? { force: true } : { alter: true };
      await sequelize.sync(syncOptions);
      console.log('✅ 数据库模型同步完成');
    }

    return true;

  } catch (error) {
    console.error('\n❌ 数据库连接失败:');
    
    // 更详细的错误分类提示
    if (error.name === 'SequelizeAccessDeniedError') {
      console.error('💡 原因：用户名或密码错误，请检查DB_USER和DB_PASS配置');
    } else if (error.name === 'SequelizeConnectionRefusedError') {
      console.error('💡 原因：无法连接到数据库服务器，请检查DB_HOST和DB_PORT是否正确，以及服务器是否可访问');
    } else if (error.name === 'SequelizeConnectionError') {
      console.error(`💡 原因：数据库连接错误 - ${error.original?.sqlMessage || error.message}`);
    } else {
      console.error('💡 错误详情:', error.message);
    }
    
    process.exit(1);
  }
};

module.exports = { sequelize, connectDB, dbConfig };
